<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>双股票投资对比走势图</title>
    <script src="../assets/js/echarts.js"></script>
    <script src="../assets/js/util.js"></script>
    <link rel="stylesheet" href="../assets/css/common.css" />
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>双股票投资对比走势图</h1>
            <p class="subtitle">可视化两只股票的投资增长对比</p>
        </div>

        <div class="config-panel">
            <div class="config-row">
                <div class="config-item">
                    <label for="start-date">开始日期</label>
                    <input type="date" id="start-date" value="2022-01-01">
                </div>
                <div class="config-item">
                    <label for="end-date">结束日期</label>
                    <input type="date" id="end-date" value="2025-09-01">
                </div>
                <div class="config-item">
                    <label for="investment-amount">投资金额(元)</label>
                    <input type="number" id="investment-amount" value="1000000">
                </div>
                <div class="config-item">
                    <label for="animation-speed">动画速度</label>
                    <input type="range" id="animation-speed" min="10" max="500" value="150">
                </div>
            </div>

            <div class="stock-config-group">
                <div class="stock-config">
                    <h3>股票1配置</h3>
                    <div class="config-row">
                        <div class="config-item">
                            <label for="stock1-name">股票名称</label>
                            <input type="text" id="stock1-name" value="紫金矿业">
                        </div>
                        <div class="config-item">
                            <label for="stock1-code">股票代码</label>
                            <input type="text" id="stock1-code" value="601899">
                        </div>
                        <div class="config-item">
                            <label for="stock1-color">折线颜色</label>
                            <input type="color" id="stock1-color" value="#FFD700">
                        </div>
                    </div>
                </div>

                <div class="stock-config">
                    <h3>股票2配置</h3>
                    <div class="config-row">
                        <div class="config-item">
                            <label for="stock2-name">股票名称</label>
                            <input type="text" id="stock2-name" value="贵州茅台">
                        </div>
                        <div class="config-item">
                            <label for="stock2-code">股票代码</label>
                            <input type="text" id="stock2-code" value="600519">
                        </div>
                        <div class="config-item">
                            <label for="stock2-color">折线颜色</label>
                            <input type="color" id="stock2-color" value="#ff4757">
                        </div>
                    </div>
                </div>
            </div>

            <div class="config-row">
                <div class="config-item">
                    <label for="shadow-opacity">阴影透明度</label>
                    <input type="range" id="shadow-opacity" min="0" max="100" value="30">
                </div>
                <div class="config-item">
                    <label for="chart-bg-color">图表背景色</label>
                    <input type="color" id="chart-bg-color" value="#000000">
                </div>
                <div class="config-item">
                    <label for="info-panel-color">总资产背景色</label>
                    <input type="color" id="info-panel-color" value="#000000">
                </div>
                <div class="config-item">
                    <label for="page-bg-color">网页背景色</label>
                    <input type="color" id="page-bg-color" value="#1a2a6c">
                </div>
            </div>
            <div class="config-row">
                <button class="btn" onclick="applyConfig()">应用配置</button>
            </div>
        </div>
        <br>
        <br>
        <br>

        <div class="info-panel" id="info-panel">
            <div class="stock-info" id="stock1-info">
                <div id="stock1-name-display">紫金矿业</div>
                <div id="stock1-value" class="current-value">¥1,000,000</div>
                <div id="stock1-profit-loss" class="profit-loss"></div>
            </div>
            <div class="stock-info" id="stock2-info">
                <div id="stock2-name-display">贵州茅台</div>
                <div id="stock2-value" class="current-value">¥1,000,000</div>
                <div id="stock2-profit-loss" class="profit-loss"></div>
            </div>
        </div>

        <div class="text-panel">
            <div class="text-line-1" id="investment-text">假如2022年各买100万</div>
            <div class="text-line-2" id="date-range-text">截至2025-09-11后复权</div>
<!--            <div class="text-line-3" id="stock-name-text">PK</div>-->
        </div>

        <div class="chart-container" id="chart-container-wrapper">
            <div id="chart-container" style="width: 100%; height: 100%;"></div>
            <div id="loading" class="loading">数据加载中...</div>
        </div>
        <div class="text-panel">
            <div class="text-line-4">理财有风险，投资需谨慎</div>
        </div>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <div class="instructions">
            <p>点击图表可暂停/继续动画 | 按空格键暂停/继续 | 按R键重新开始</p>
        </div>

        <div class="controls">
            <button class="btn" onclick="toggleAnimation()">暂停/继续</button>
            <button class="btn" onclick="resetAnimation()">重新开始</button>
        </div>
    </div>

    <script>
        // ================== 全局变量 ==================
        let myChart;
        let rawData1 = [];
        let rawData2 = [];
        let animatedData1 = [];
        let animatedData2 = [];
        let currentIndex = 0;
        let animationInterval;
        let animationSpeed = 300;
        let investmentAmount = 1000000;
        let isAnimationComplete = false;

        // 股票1配置
        let stock1Code = '601899';
        let stock1Name = '紫金矿业';
        let stock1Color = '#FFD700';

        // 股票2配置
        let stock2Code = '600519';
        let stock2Name = '贵州茅台';
        let stock2Color = '#FFD700';

        // 通用配置
        let startDate = '2022-01-01';
        let endDate = '2025-09-11';
        let chartBgColor = '#000000';
        let infoPanelColor = '#000000';
        let pageBgColor = '#1a2a6c';
        let shadowOpacity = 30;
        let allDates = [];

        // ================== 入口 ==================
        function init() {
            initializeChart();
            updateTextElements();
            updateColors();
            loadData();
            setupEventListeners();
        }

        // ================== 更新文本元素 ==================
        function updateTextElements() {
            investmentAmount = parseInt(document.getElementById('investment-amount').value) || 1000000;
            startDate = document.getElementById('start-date').value;
            endDate = document.getElementById('end-date').value;

            const formattedAmount = (investmentAmount / 10000).toFixed(0);

            document.getElementById('investment-text').textContent =
                `假如${startDate.substring(0, 4)}年各买${formattedAmount}万`;
            document.getElementById('date-range-text').textContent =
                `截至${endDate}后复权`;
<!--            document.getElementById('stock-name-text').textContent = "PK";-->

            // 更新股票名称显示
            document.getElementById('stock1-name-display').textContent = stock1Name;
            document.getElementById('stock2-name-display').textContent = stock2Name;
        }

        // ================== 更新颜色配置 ==================
        function updateColors() {
            stock1Color = document.getElementById('stock1-color').value;
            stock2Color = document.getElementById('stock2-color').value;
            chartBgColor = document.getElementById('chart-bg-color').value;
            infoPanelColor = document.getElementById('info-panel-color').value;
            pageBgColor = document.getElementById('page-bg-color').value;
            shadowOpacity = parseInt(document.getElementById('shadow-opacity').value);

            document.getElementById('chart-container-wrapper').style.backgroundColor = chartBgColor;
            document.getElementById('info-panel').style.backgroundColor = infoPanelColor;
            document.body.style.background = pageBgColor;

            // 更新股票信息颜色
            document.getElementById('stock1-info').style.color = stock1Color;
            document.getElementById('stock2-info').style.color = stock2Color;

            if (myChart) {
                updateChartColors();
            }
        }

        // 更新图表颜色
        function updateChartColors() {
            const shadowAlpha = (shadowOpacity / 100).toFixed(2);
            const areaAlpha = (shadowOpacity / 100 * 0.3).toFixed(2);

            myChart.setOption({
                series: [
                    {
                        lineStyle: {
                            color: stock1Color,
                            shadowColor: stock1Color
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: hexToRgba(stock1Color, areaAlpha)
                                }, {
                                    offset: 1,
                                    color: hexToRgba(stock1Color, 0)
                                }]
                            }
                        }
                    },
                    {
                        lineStyle: {
                            color: stock2Color,
                            shadowColor: stock2Color
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: hexToRgba(stock2Color, areaAlpha)
                                }, {
                                    offset: 1,
                                    color: hexToRgba(stock2Color, 0)
                                }]
                            }
                        }
                    }
                ]
            });
        }

        // ================== 图表初始化 ==================
        function initializeChart() {
            const chartDom = document.getElementById('chart-container');
            myChart = echarts.init(chartDom);

            const shadowAlpha = (shadowOpacity / 100).toFixed(2);
            const areaAlpha = (shadowOpacity / 100 * 0.3).toFixed(2);

            const option = {
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(0,0,0,.9)',
                    borderColor: '#FFD700',
                    borderWidth: 1,
                    textStyle: { color: '#fff', fontSize: 16 },
                    formatter: (params) => {
                        let result = `日期: ${params[0].name}<br/>`;
                        params.forEach(param => {
                            result += `${param.seriesName}: ¥${param.value.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}<br/>`;
                        });
                        return result;
                    }
                },
                legend: {
                    data: [stock1Name, stock2Name],
                    textStyle: { color: '#fff' },
                    top: 10
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    top: '15%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    axisLine: {
                        lineStyle: { color: '#FFFFFF', width: 2 }
                    },
                    axisLabel: {
                        rotate: 45,
                        color: '#FFFFFF',
                        fontSize: 8,
                        margin: 15
                    },
                    axisTick: {
                        alignWithLabel: true,
                        lineStyle: { color: '#FFFFFF' }
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: { color: '#FFFFFF', width: 2 }
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: 'rgba(255,255,255,0.2)'
                        }
                    },
                    axisLabel: {
                        color: '#FFFFFF',
                        fontSize: 10,
                        formatter: function(value) {
                            if (value >= 1000000) {
                                return '¥' + (value / 1000000).toFixed(2) + 'M';
                            }
                            return '¥' + value;
                        }
                    }
                },
                series: [
                    {
                        name: stock1Name,
                        type: 'line',
                        data: [],
                        showSymbol: false,
                        smooth: true,
                        lineStyle: {
                            width: 2,
                            color: stock1Color,
                            shadowBlur: 15,
                            shadowColor: hexToRgba(stock1Color, shadowAlpha)
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: hexToRgba(stock1Color, areaAlpha)
                                }, {
                                    offset: 1,
                                    color: hexToRgba(stock1Color, 0)
                                }]
                            }
                        }
                    },
                    {
                        name: stock2Name,
                        type: 'line',
                        data: [],
                        showSymbol: false,
                        smooth: true,
                        lineStyle: {
                            width: 2,
                            color: stock2Color,
                            shadowBlur: 15,
                            shadowColor: hexToRgba(stock2Color, shadowAlpha)
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: hexToRgba(stock2Color, areaAlpha)
                                }, {
                                    offset: 1,
                                    color: hexToRgba(stock2Color, 0)
                                }]
                            }
                        }
                    }
                ],
                backgroundColor: 'rgba(0,0,0,0.1)'
            };

            myChart.setOption(option);
        }

        // ================== 数据加载 ==================
        async function loadData() {
            try {
                document.getElementById('loading').style.display = 'block';

                // 获取最新配置
                stock1Code = document.getElementById('stock1-code').value;
                stock1Name = document.getElementById('stock1-name').value;
                stock2Code = document.getElementById('stock2-code').value;
                stock2Name = document.getElementById('stock2-name').value;
                startDate = document.getElementById('start-date').value;
                endDate = document.getElementById('end-date').value;
                investmentAmount = parseInt(document.getElementById('investment-amount').value) || 1000000;
                animationSpeed = 550 - parseInt(document.getElementById('animation-speed').value);

                // 更新文本显示和颜色
                updateTextElements();
                updateColors();

                // 同时获取两只股票的数据
                const [data1, data2] = await Promise.all([
                    fetchStockData(stock1Code, stock1Name),
                    fetchStockData(stock2Code, stock2Name)
                ]);

                rawData1 = data1;
                rawData2 = data2;

                // 获取所有日期并排序
                allDates = Array.from(new Set([
                    ...rawData1.map(item => item.date),
                    ...rawData2.map(item => item.date)
                ])).sort();

                // 确保两只股票数据有相同的日期范围
                alignDataByDate();

                animatedData1 = [rawData1[0]];
                animatedData2 = [rawData2[0]];

                document.getElementById('loading').style.display = 'none';

                updateChartDisplay();
                updateInfoPanel();

                // 自动开始动画
                setTimeout(() => startAnimation(), 1000);

            } catch (err) {
                console.error('加载数据失败:', err);
                document.getElementById('loading').innerHTML =
                    `<span class="error">加载失败: ${err.message}</span>`;
                document.getElementById('stock1-value').textContent = '加载失败';
                document.getElementById('stock2-value').textContent = '加载失败';
                document.getElementById('stock1-value').style.color = '#ff4757';
                document.getElementById('stock2-value').style.color = '#ff4757';
            }
        }

        // 获取单只股票数据
        async function fetchStockData(stockCode, stockName) {
            // const apiUrl = `http://192.168.2.51:5001/api/data?symbol=${stockCode}&start_date=${startDate}&end_date=${endDate}`;
            const apiUrl = `http://127.0.0.1:8888/api/stock/daily`;

            const res = await fetch(apiUrl,{
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({"ts_code": addSuffix(stockCode),"start_date":formatDateToNumber(startDate),"end_date":formatDateToNumber(endDate),"adi":"1"})
            });
            console.log(`请求API: ${apiUrl}`);

            // const res = await fetch(apiUrl);
            if (!res.ok) throw new Error(`获取${stockName}数据失败`);

            const json = await res.json();
            if (json.code !== 0) throw new Error(json.msg || `API返回${stockName}数据错误`);

            if (!json.data || json.data.length === 0) {
                throw new Error(`${stockName}返回数据为空`);
            }

            // const initialPrice = json.data[0][1];
            // return json.data.map(([date, price]) => ({
            //     date: formatDate(date),
            //     total: (price / initialPrice) * investmentAmount
            // }));
            const originalData = json.data.reverse();
            const initialPrice = originalData[0].close;
            return originalData.map((item) => ({
                date: formatDate(item.trade_date),
                total: (item.close / initialPrice) * investmentAmount
            }));
        }

        // 对齐数据日期
        function alignDataByDate() {
            const alignedData1 = [];
            const alignedData2 = [];

            allDates.forEach(date => {
                // 查找股票1在该日期的数据
                const data1 = rawData1.find(item => item.date === date);
                // 查找股票2在该日期的数据
                const data2 = rawData2.find(item => item.date === date);

                // 如果两只股票都有该日期的数据，则添加到对齐后的数据中
                if (data1 && data2) {
                    alignedData1.push(data1);
                    alignedData2.push(data2);
                }
            });

            rawData1 = alignedData1;
            rawData2 = alignedData2;
        }

        // 应用配置
        function applyConfig() {
            clearInterval(animationInterval);
            animationInterval = null;

            rawData1 = [];
            rawData2 = [];
            animatedData1 = [];
            animatedData2 = [];
            currentIndex = 0;
            isAnimationComplete = false;

            loadData();
        }

        // 计算动态Y轴范围
        function calculateDynamicYAxisRange(data1, data2) {
            if (data1.length === 0 || data2.length === 0) return { min: 0, max: 100000 };

            const values1 = data1.map(d => d.total);
            const values2 = data2.map(d => d.total);

            const allValues = [...values1, ...values2];
            const minValue = Math.min(...allValues);
            const maxValue = Math.max(...allValues);

            const range = maxValue - minValue;
            const marginBottom = range * 0.1;
            const marginTop = range * 0.3;

            return {
                min: Math.floor(minValue - marginBottom),
                max: Math.ceil(maxValue + marginTop)
            };
        }

        // ================== 图表更新 ==================
        function updateChartDisplay() {
            let displayData1, displayData2;
            let xAxisData;
            let yAxisConfig;

            if (isAnimationComplete) {
                // 动画完成：显示全部数据
                displayData1 = animatedData1;
                displayData2 = animatedData2;
                xAxisData = allDates;
                yAxisConfig = {
                    min: null,
                    max: null
                };
            } else {
                // 动画中：显示最近10条数据
                displayData1 = getRecent10Data(animatedData1);
                displayData2 = getRecent10Data(animatedData2);

                // 获取最近10个日期
                const recentDates = allDates.slice(
                    Math.max(0, currentIndex - 10),
                    currentIndex
                );
                xAxisData = recentDates;

                // 动态计算Y轴范围
                const yRange = calculateDynamicYAxisRange(displayData1, displayData2);
                yAxisConfig = {
                    min: yRange.min,
                    max: yRange.max
                };
            }

            const chartData1 = displayData1.map(d => ({
                name: d.date,
                value: d.total
            }));

            const chartData2 = displayData2.map(d => ({
                name: d.date,
                value: d.total
            }));

            myChart.setOption({
                legend: {
                    data: [stock1Name, stock2Name]
                },
                xAxis: {
                    data: xAxisData,
                    axisLabel: {
                        interval: isAnimationComplete ? 'auto' : 0
                    }
                },
                yAxis: yAxisConfig,
                series: [
                    {
                        name: stock1Name,
                        data: chartData1,
                        smooth: !isAnimationComplete
                    },
                    {
                        name: stock2Name,
                        data: chartData2,
                        smooth: !isAnimationComplete
                    }
                ]
            });
        }

        // ================== 信息面板 ==================
        function updateInfoPanel() {
            if (!animatedData1.length || !animatedData2.length) return;

            const cur1 = animatedData1[animatedData1.length - 1];
            const cur2 = animatedData2[animatedData2.length - 1];

            const currentValue1 = cur1.total;
            const currentValue2 = cur2.total;

            document.getElementById('stock1-value').textContent =
                '¥' + currentValue1.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            document.getElementById('stock2-value').textContent =
                '¥' + currentValue2.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',');

            // 更新盈亏信息
            updateProfitLossInfo('stock1', currentValue1);
            updateProfitLossInfo('stock2', currentValue2);
        }

        // 更新单只股票的盈亏信息
        function updateProfitLossInfo(stockPrefix, currentValue) {
            const profitLoss = currentValue - investmentAmount;
            const percentChange = ((profitLoss / investmentAmount) * 100).toFixed(2);
            const profitLossElement = document.getElementById(`${stockPrefix}-profit-loss`);

            if (profitLoss !== 0) {
                profitLossElement.innerHTML =
                    `${profitLoss >= 0 ? '盈利' : '亏损'}: ¥${Math.abs(profitLoss).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')} (${percentChange}%)`;
                profitLossElement.style.color = profitLoss >= 0 ? '#ff4757' : '#00b894';
            } else {
                profitLossElement.innerHTML = '';
            }
        }

        // ================== 动画控制 ==================
        function startAnimation() {
            if (currentIndex >= allDates.length) {
                completeAnimation();
                return;
            }

            clearInterval(animationInterval);

            animationInterval = setInterval(() => {
                if (currentIndex >= allDates.length) {
                    completeAnimation();
                    return;
                }

                const currentDate = allDates[currentIndex];

                // 添加当前日期的数据
                const data1 = rawData1.find(item => item.date === currentDate);
                const data2 = rawData2.find(item => item.date === currentDate);

                if (data1) animatedData1.push(data1);
                if (data2) animatedData2.push(data2);

                updateChartDisplay();
                updateInfoPanel();
                currentIndex++;

            }, animationSpeed);
        }

        // 动画完成处理
        function completeAnimation() {
            clearInterval(animationInterval);
            isAnimationComplete = true;

            updateChartDisplay();

            // 添加完成提示
            const finalValue1 = animatedData1[animatedData1.length - 1].total;
            const finalValue2 = animatedData2[animatedData2.length - 1].total;

            updateFinalProfitLossInfo('stock1', finalValue1);
            updateFinalProfitLossInfo('stock2', finalValue2);
        }

        // 更新最终盈亏信息
        function updateFinalProfitLossInfo(stockPrefix, finalValue) {
            const profitLoss = finalValue - investmentAmount;
            const percentChange = ((profitLoss / investmentAmount) * 100).toFixed(2);
            const profitLossElement = document.getElementById(`${stockPrefix}-profit-loss`);

            profitLossElement.innerHTML =
                `最终${profitLoss >= 0 ? '盈利' : '亏损'}: ¥${Math.abs(profitLoss).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')} (${percentChange}%)`;
            profitLossElement.style.color = profitLoss >= 0 ? '#ff4757' : '#00b894';
            profitLossElement.style.fontSize = '1.2rem';
        }

        // 重置动画
        function resetAnimation() {
            clearInterval(animationInterval);
            animatedData1 = [rawData1[0]];
            animatedData2 = [rawData2[0]];
            currentIndex = 1;
            isAnimationComplete = false;

            // 移除完成提示的样式
            document.getElementById('stock1-profit-loss').style.fontSize = '';
            document.getElementById('stock2-profit-loss').style.fontSize = '';

            updateChartDisplay();
            updateInfoPanel();
            startAnimation();
        }

        // 切换动画状态
        function toggleAnimation() {
            if (isAnimationComplete) return;

            if (animationInterval) {
                clearInterval(animationInterval);
                animationInterval = null;
            } else {
                startAnimation();
            }
        }

        // ================== 事件绑定 ==================
        function setupEventListeners() {
            window.addEventListener('resize', () => {
                if (myChart) myChart.resize();
            });

            const chartDom = document.getElementById('chart-container');
            chartDom.addEventListener('click', () => {
                if (isAnimationComplete) return;
                toggleAnimation();
            });

            document.addEventListener('keydown', (e) => {
                if (e.code === 'Space') {
                    e.preventDefault();
                    if (isAnimationComplete) return;
                    toggleAnimation();
                } else if (e.code === 'KeyR') {
                    e.preventDefault();
                    resetAnimation();
                }
            });

            // 颜色选择器变化时实时更新
            document.getElementById('stock1-color').addEventListener('input', updateColors);
            document.getElementById('stock2-color').addEventListener('input', updateColors);
            document.getElementById('chart-bg-color').addEventListener('input', updateColors);
            document.getElementById('info-panel-color').addEventListener('input', updateColors);
            document.getElementById('page-bg-color').addEventListener('input', updateColors);
            document.getElementById('shadow-opacity').addEventListener('input', updateColors);
        }

        // ================== 页面启动 ==================
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>